﻿using System;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Text;

namespace SweetSurvey.Models.Repositories
{
    /// <summary>
    /// The base class for all repositories.
    /// </summary>
    public abstract class RepositoryBase
    {
        private const int ID_LENGTH = 6;
        private static Random random = new Random();

        /// <summary>
        /// Generate a random id.
        /// </summary>
        /// <returns>Random id.</returns>
        public static string GenerateRandomId()
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < ID_LENGTH; i++)
            {
                builder.Append(GenerateRandomCharacter());
            }
            return builder.ToString();
        }

        /// <summary>
        /// Generate a random character.
        /// </summary>
        /// <returns>Random character.</returns>
        private static char GenerateRandomCharacter()
        {
            char ch;
            if (random.Next(2) == 0) { ch = 'a'; }
            else { ch = 'A'; }
            return (char)((int)ch + random.Next(26));
        }

        public static void Update(EntityObject entity, EntityState state = EntityState.Modified)
        {
            var context = new SweetSurveyModelContainer();
            context.Attach(entity);
            context.ObjectStateManager.ChangeObjectState(entity, state);
            context.SaveChanges();
            if (entity.EntityState != EntityState.Detached) { context.Detach(entity); }
        }

        public static void Delete(EntityObject entity)
        {
            Update(entity, EntityState.Deleted);
        }
    }
}